<template>
  <div class="upload">
    <a-spin tip="Loading..." :spinning="loading">
      <a-upload
        action=""
        :disabled="disabled"
        listType="picture-card"
        :beforeUpload="beforeUpload"
        :remove="remove"
        :fileList="fileList"
        @preview="handlePreview"
        @change="imageChange"
      >
        <div v-if="fileList.length < maxLength">
          <a-icon type="plus" />
          <div class="ant-upload-text">上传图片</div>
        </div>
      </a-upload>
    </a-spin>
    <a-modal :visible="previewVisible" :footer="null" @cancel="handleCancel">
      <img alt="example" style="width: 100%" :src="previewImage" />
    </a-modal>
  </div>
</template>

<script>
import http from "@/api/common";
import { guid, getBase64 } from "@/utils";

export default {
  model: {
    prop: "value",
    event: "change"
  },
  props: {
    images: {
      type: Array,
      required: false,
      default: () => []
    },
    maxSize: {
      type: Number,
      required: false,
      default: 2400
    },
    maxLength: {
      type: Number,
      default: 1
    },
    disabled: {
      type: Boolean,
      required: false,
      default: false
    }
  },
  data() {
    return {
      fileList: [],
      previewVisible: false,
      previewImage: "",
      loading: false
    };
  },
  watch: {
    images: {
      immediate: false,
      handler() {
        if (Array.isArray(this.images) && this.images.length) {
          this.fileList = Object.assign([], this.images);
        } else {
          this.fileList = [];
        }
      }
    }
  },
  methods: {
    remove(files) {
      this.$emit("remove", files);
    },
    handleCancel() {
      this.previewVisible = false;
    },
    async handlePreview(file) {
      if (!file.url && !file.preview) {
        file.preview = await getBase64(file.originFileObj);
      }
      this.previewImage = file.url || file.preview;
      this.previewVisible = true;
    },
    imageChange({ fileList }) {
      //数据为空 清空model数据
      if (!fileList.length) {
        this.fileList = fileList;
        this.$emit("change", []);
      }
    },
    beforeUpload(file) {
      const imgCheck = /image/.test(file.type);
      const imgTypeCheck = /(.jpg|.jpeg|.png|.gif)$/.test(file.type);
      if (!imgCheck || !imgTypeCheck) {
        this.$message.error("不支持该图片格式，请更换格式重新上传。");
        return Promise.reject();
      }
      const isLt3M = file.size / 1024 <= this.maxSize;
      if (!isLt3M) {
        this.$message.error(`请选择${this.maxSize}KB以内图片`);
        return Promise.reject();
      } else {
        //接口调用 返回图片地址
        this.loading = true;
        let form = new FormData();
        form.append("file", file);

        http
          .uploadFile(form)
          .then((res) => {
            this.loading = false;
            if (res.retcode === 0) {
              let data = res.data || {};
              if (data) {
                this.fileList = [
                  {
                    uid: guid(),
                    name: "image.png",
                    status: "done",
                    url: data.url,
                    picFileId: data.ossFileId
                  }
                ];
                this.$emit("change", this.fileList);
              } else {
                this.$message.info("返回数据为空");
              }
            } else {
              this.$message.error(res.msg);
            }
          })
          .catch((err) => {
            this.loading = false;
            this.$message.error(err.msg || "上传失败");
          });
        return false;
      }
    }
  }
};
</script>

<style lang="less" scoped>
/deep/.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

/deep/.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}

/deep/.ant-modal-close-x {
  width: 26px;
  height: 26px;
  line-height: 26px;
}
/deep/ .ant-upload-picture-card-wrapper {
  display: flex;
  flex-wrap: wrap;
}
</style>
